<template>
  <div class="rest-area">
    <el-row :gutter="20">
      <!-- 左侧休息计时区域 -->
      <el-col :span="16">
        <el-card class="rest-timer-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>休息时间</span>
              <el-tag :type="isResting ? 'success' : 'info'">
                {{ isResting ? "休息中" : "待开始" }}
              </el-tag>
            </div>
          </template>

          <div class="timer-section">
            <div class="timer-display">
              {{ formatTime(currentTime) }}
            </div>
            <div class="timer-progress">
              <el-progress
                :percentage="timerProgress"
                :status="isResting ? 'success' : ''"
                :stroke-width="12"
                :show-text="false"
              />
            </div>
            <div class="timer-controls">
              <el-button-group>
                <el-button
                  type="primary"
                  :icon="isResting ? 'VideoPause' : 'VideoPlay'"
                  size="large"
                  @click="isResting ? pauseRest() : startRest()"
                >
                  {{ isResting ? "暂停" : "开始休息" }}
                </el-button>
                <el-button
                  type="danger"
                  icon="CircleClose"
                  size="large"
                  @click="endRest"
                >
                  结束休息
                </el-button>
              </el-button-group>
            </div>
          </div>

          <!-- 休息建议 -->
          <div class="rest-suggestions">
            <h3>休息建议</h3>
            <el-row :gutter="20">
              <el-col
                :span="8"
                v-for="suggestion in restSuggestions"
                :key="suggestion.id"
              >
                <el-card
                  class="suggestion-card"
                  shadow="hover"
                  :class="{ active: currentSuggestion === suggestion.id }"
                  @click="selectSuggestion(suggestion)"
                >
                  <div class="suggestion-icon">
                    <el-icon>
                      <component :is="suggestion.icon" />
                    </el-icon>
                  </div>
                  <div class="suggestion-content">
                    <h4>{{ suggestion.title }}</h4>
                    <p>{{ suggestion.description }}</p>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-card>

        <!-- 休息记录 -->
        <el-card class="rest-records" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>休息记录</span>
              <el-radio-group v-model="recordType" size="small">
                <el-radio-button label="today">今日</el-radio-button>
                <el-radio-button label="week">本周</el-radio-button>
              </el-radio-group>
            </div>
          </template>

          <el-timeline-item
            v-for="record in restRecords"
            :key="record.id"
            :timestamp="record.time"
            :type="record.type"
          >
            <h4>{{ record.activity }}</h4>
            <p>建议时长：{{ record.suggestionDuration }}</p>
            <p class="actual-time">
              实际休息时间：
              <span
                v-if="record.status === '中断'"
                class="interrupted-duration"
                >{{ record.actualDuration }}</span
              >
              <span v-else>{{ record.actualDuration }}</span>
            </p>
            <el-tag size="small" :type="record.type">{{
              record.status
            }}</el-tag>
          </el-timeline-item>
        </el-card>
      </el-col>

      <!-- 右侧状态区域 -->
      <el-col :span="8">
        <!-- 状态监测 -->
        <el-card class="status-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>状态监测</span>
              <!-- <el-button type="primary" link @click="refreshStatus">
                刷新状态
              </el-button> -->
            </div>
          </template>

          <div class="status-items">
            <div v-for="status in healthStatus" :key="status.type">
              <el-tooltip
                class="status-item"
                effect="dark"
                :content="status.tips"
                placement="top-start"
              >
                <div>
                  <div class="status-info">
                    <div class="status-label">{{ status.label }}</div>
                    <el-progress
                      :percentage="status.value"
                      :status="status.status"
                      :stroke-width="8"
                    />
                  </div>
                </div>
              </el-tooltip>
            </div>
          </div>
        </el-card>

        <!-- 环境建议 -->
        <el-card class="environment-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>环境建议</span>
            </div>
          </template>

          <el-collapse v-model="activeEnvTips">
            <el-collapse-item
              v-for="tip in environmentTips"
              :key="tip.id"
              :title="tip.title"
              :name="tip.id"
            >
              <div class="tip-content">
                <p>{{ tip.content }}</p>
                <div class="tip-value">
                  <el-tag :type="tip.status">{{ tip.value }}</el-tag>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import { restApi } from "@/api/rest";
import { studyApi } from "@/api/study";
// 基础状态
const isResting = ref(false);
const currentTime = ref(0);
const timerProgress = ref(0);
const currentRestRecord = ref(null);
let timer = null;

// 休息建议数据
const restSuggestions = ref([
  {
    id: "eye",
    title: "眼部放松",
    description: "远眺放松眼部肌肉，每20分钟看远处20秒",
    icon: "View",
    duration: 300,
    tips: ["闭眼轻揉太阳穴", "远眺绿色植物", "做眼部按摩", "眨眼练习"],
  },
  {
    id: "stretch",
    title: "伸展运动",
    description: "活动颈椎和手腕，预防职业病",
    icon: "Position",
    duration: 180,
    tips: ["颈部拉伸", "肩膀放松", "手腕活动", "站立伸展"],
  },
  {
    id: "meditation",
    title: "冥想放松",
    description: "深呼吸放松身心，缓解压力",
    icon: "MagicStick",
    duration: 300,
    tips: ["正确坐姿", "深呼吸", "放空思维", "专注呼吸"],
  },
  {
    id: "walk",
    title: "散步放松",
    description: "适当走动，促进血液循环",
    icon: "Position",
    duration: 300,
    tips: ["室内慢走", "上下楼梯", "原地踏步", "伸展活动"],
  },
  {
    id: "water",
    title: "喝水休息",
    description: "补充水分，避免久坐",
    icon: "Coffee",
    duration: 180,
    tips: ["补充温水", "泡杯茶", "站立喝水", "调整呼吸"],
  },
  {
    id: "social",
    title: "社交休息",
    description: "短暂交谈，放松心情",
    icon: "ChatDotRound",
    duration: 300,
    tips: ["同事交流", "打个电话", "发条消息", "聊天放松"],
  },
]);

const currentSuggestion = ref(null);

// 休息记录
const recordType = ref("today");
const restRecords = ref([]);

// 健康状态数据
const healthStatus = ref([
  {
    type: "energy",
    label: "精力值",
    value: 85,
    status: "success",
    icon: "Lightning",
    tips: "当前精力充沛，适合学习",
  },
  {
    type: "eyes",
    label: "用眼疲劳",
    value: 65,
    status: "warning",
    icon: "View",
    tips: "建议及时休息，避免用眼过度",
  },
  {
    type: "posture",
    label: "坐姿状态",
    value: 90,
    status: "success",
    icon: "Position",
    tips: "保持良好坐姿，预防颈椎问题",
  },
  {
    type: "focus",
    label: "专注度",
    value: 75,
    status: "success",
    icon: "Aim",
    tips: "当前注意力集中，可以继续学习",
  },
]);

// 环境建议数据
const environmentTips = ref([
  {
    id: 1,
    title: "光线情况",
    content: "建议保持500-1000勒克斯的照明度，避免眼疲劳。",
    value: "650 lux",
    status: "success",
    icon: "Sunny",
  },
  {
    id: 2,
    title: "噪音水平",
    content: "环境较为安静，有利于专注。建议保持在45分贝以下的环境噪音水平。",
    value: "35 dB",
    status: "success",
    icon: "Bell",
  },
  {
    id: 3,
    title: "温度",
    content: "室温适宜，注意保持通风。建议将室温维持在20-26℃之间。",
    value: "24℃",
    status: "success",
    icon: "Thermometer",
  },
  {
    id: 4,
    title: "湿度",
    content: "适中的`空气湿度，有助于保持舒适。建议相对湿度保持在40-60%之间。",
    value: "45%",
    status: "success",
    icon: "Watermelon",
  },
]);

const activeEnvTips = ref(["1"]);

// 方法
const formatTime = (ms) => {
  const totalSeconds = Math.floor(ms / 1000);
  const minutes = Math.floor(totalSeconds / 60);
  const seconds = totalSeconds % 60;
  return `${String(minutes).padStart(2, "0")}:${String(seconds).padStart(
    2,
    "0"
  )}`;
};

const userId = ref(localStorage.getItem("userId") || null); // 从本地存储获取用户ID
const studyRecords = ref([]); // 学习记录数据
// 健康指标状态计算函数
const calculateStatus = (value) => {
  if (value >= 80) return { status: "success", level: "高" };
  if (value >= 60) return { status: "warning", level: "中" };
  return { status: "exception", level: "低" };
};

// 健康指标建议生成器
const generateTips = (type, value) => {
  const status = calculateStatus(value);

  const tipsMap = {
    vitality: {
      success: "当前精力充沛，适合高效学习或工作",
      warning: "注意劳逸结合，建议适当休息",
      exception: "精力不足，请及时休息恢复",
    },
    eyeFatigue: {
      success: "用眼状态良好，继续保持",
      warning: "用眼疲劳度中等，建议做眼保健操",
      exception: "用眼过度，请立即休息眼睛",
    },
    standStrength: {
      success: "站立/活动充足，保持得很好",
      warning: "站立/活动量一般，建议多起身活动",
      exception: "久坐时间过长，对健康不利",
    },
    concentration: {
      success: "专注力优秀，学习效率高",
      warning: "专注力一般，建议调整工作环境",
      exception: "难以集中注意力，需要休息或改变任务",
    },
  };

  return tipsMap[type][status.status];
};

// 获取健康数据的主函数
const getHealthData = async () => {
  try {
    await fetchRecords();
    const result = calculateVitality(studyRecords.value, resetRecords2.value);

    console.log("今日健康报告:");
    console.log(`元气值: ${result.vitality}`);
    console.log(`用眼疲劳度: ${result.eyeFatigue}`);
    console.log(`站立强度: ${result.standStrength}`);
    console.log(`专注度: ${result.concentration}`);

    // 健康指标配置
    const healthMetrics = [
      { key: "vitality", name: "元气值", value: result.vitality },
      { key: "eyeFatigue", name: "用眼疲劳度", value: result.eyeFatigue },
      { key: "standStrength", name: "站立强度", value: result.standStrength },
      { key: "concentration", name: "专注度", value: result.concentration },
    ];

    // 更新健康状态
    healthMetrics.forEach((metric, index) => {
      const statusInfo = calculateStatus(metric.value);

      healthStatus.value[index] = {
        ...healthStatus.value[index],
        value: metric.value,
        status: statusInfo.status,
        tips: generateTips(metric.key, metric.value),
        level: statusInfo.level,
      };
    });
  } catch (error) {
    console.error("获取健康数据失败:", error);
    // 可以在这里添加错误处理逻辑，如显示错误提示等
  }
};
// 获取学习记录
const fetchRecords = async () => {
  try {
    const response = await studyApi.getStudyRecords();
    // 正确处理分页响应
    studyRecords.value = response.results || []; // 使用 results 数组
  } catch (error) {
    ElMessage.error("获取学习记录失败");
    studyRecords.value = [];
  }
};
const startRest = async () => {
  if (!currentSuggestion.value) {
    ElMessage.warning("请先选择休息活动");
    return;
  }

  try {
    const suggestion = restSuggestions.value.find(
      (s) => s.id === currentSuggestion.value
    );
    const response = await restApi.createRestRecord({
      user_id: userId.value,
      category: suggestion.id,
      duration: suggestion.duration,
      flag: "completed",
    });
    currentRestRecord.value = response;
    isResting.value = true;
    timer = setInterval(() => {
      currentTime.value += 1000;
      timerProgress.value =
        (currentTime.value / (suggestion.duration * 1000)) * 100;

      if (currentTime.value >= suggestion.duration * 1000) {
        endRest(true);
        ElMessage.success("休息完成！");
      }
    }, 1000);
  } catch (error) {
    ElMessage.error("开始休息失败");
  }
};

const pauseRest = () => {
  isResting.value = false;
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
};
const resetRecords2 = ref([]);
function calculateVitality(studyRecords, resetRecords) {
  // 获取今日日期
  const today = new Date().toISOString().split("T")[0];

  // 过滤今日记录
  const todayStudy = studyRecords.filter((record) =>
    record.start_time.startsWith(today)
  );
  const todayReset = resetRecords.filter((record) =>
    record.start_time.startsWith(today)
  );

  // 初始化各项指标
  let vitality = 100; // 元气值（初始100）
  let eyeFatigue = 100; // 用眼疲劳度
  let standStrength = 100; // 站立强度
  let concentration = 100; // 专注度

  // 处理学习记录
  todayStudy.forEach((record) => {
    const minutes = record.duration / 60;
    // 学习消耗元气（每4分钟-1点）
    vitality -= minutes / 4;
    // 学习消耗用眼疲劳（每分钟1点）
    eyeFatigue -= minutes;
    standStrength -= minutes / 5;
    concentration -= minutes;
  });
  // 数值范围处理，确保所有值在0-100之间
  vitality = Math.max(1, Math.min(100, Math.round(vitality)));
  eyeFatigue = Math.max(1, Math.min(100, Math.round(eyeFatigue)));
  standStrength = Math.max(1, Math.min(100, Math.round(standStrength)));
  concentration = Math.max(1, Math.min(100, Math.round(concentration)));
  // 处理休息记录
  todayReset.forEach((record) => {
    const minutes = record.actual_duration / 60;

    switch (record.category) {
      case "walk":
        vitality += minutes * 3; // 散步恢复元气
        standStrength += minutes * 20; // 站立强度增加
        eyeFatigue += minutes * 20;
        break;

      case "meditation":
        vitality += minutes * 5; // 冥想恢复元气
        concentration += minutes * 20; // 专注度增加
        break;

      case "stretch":
        vitality += minutes * 4; // 拉伸恢复元气
        standStrength += minutes * 35; // 站立强度增加
        break;

      case "eye":
        vitality += minutes * 5; // 眼部放松恢复元气
        eyeFatigue += minutes * 20; // 减少用眼疲劳
        break;

      case "water":
      case "social":
        vitality += minutes * 8; // 基础恢复
        break;
    }
  });
  // 数值范围处理，确保所有值在0-100之间
  vitality = Math.max(1, Math.min(100, Math.round(vitality)));
  eyeFatigue = Math.max(1, Math.min(100, Math.round(eyeFatigue)));
  standStrength = Math.max(1, Math.min(100, Math.round(standStrength)));
  concentration = Math.max(1, Math.min(100, Math.round(concentration)));

  return {
    vitality, // 元气值 (0-100)
    eyeFatigue, // 用眼疲劳度 (0-100)
    standStrength, // 站立强度 (0-100)
    concentration, // 专注度 (0-100)
  };
}

const endRest = async (completed = false) => {
  try {
    if (currentRestRecord.value) {
      const startTime = new Date(currentRestRecord.value.start_time);
      const endTime = new Date(currentRestRecord.value.created_at);
      const actualDuration = Math.floor((endTime - startTime) / 1000);
      await restApi.updateRestRecord(currentRestRecord.value.id, {
        flag: completed ? "completed" : "interrupted",
        actual_duration: currentTime.value / 1000,
      });
    }
  } catch (error) {
    console.log(error);

    ElMessage.error("更新休息记录失败");
  } finally {
    isResting.value = false;
    if (timer) {
      clearInterval(timer);
      timer = null;
    }
    currentTime.value = 0;
    timerProgress.value = 0;
    currentSuggestion.value = null;
    currentRestRecord.value = null;
    loadRestRecords();
  }
};

const selectSuggestion = (suggestion) => {
  if (isResting.value) return;
  currentSuggestion.value = suggestion.id;
  currentTime.value = 0;
  timerProgress.value = 0;
};

const loadRestRecords = async () => {
  try {
    const response = await restApi.getRestRecords(
      recordType.value,
      userId.value
    );
    resetRecords2.value = response;
    restRecords.value = response.map((record) => {
      const activity = restSuggestions.value.find(
        (s) => s.id === record.category
      );

      // 建议时长
      const suggestionMinutes = Math.floor(record.duration / 60);
      const suggestionSeconds = record.duration % 60;
      const suggestionText = `${suggestionMinutes}分${suggestionSeconds}秒`;

      // 实际休息时长
      let actualDurationSeconds = record.actual_duration;
      // 如果 actual_duration 为 null，前端用 created_at - start_time 补算
      if (
        actualDurationSeconds == null &&
        record.start_time &&
        record.created_at
      ) {
        const startTime = new Date(record.start_time);
        const endTime = new Date(record.created_at);
        actualDurationSeconds = Math.floor((endTime - startTime) / 1000);
      }
      if (actualDurationSeconds == null || isNaN(actualDurationSeconds))
        actualDurationSeconds = 0;

      const actualMinutes = Math.floor(actualDurationSeconds / 60);
      const actualSeconds = actualDurationSeconds % 60;
      const actualText = `${actualMinutes}分${actualSeconds}秒`;

      return {
        id: record.id,
        activity: activity?.title || "未知活动",
        time: new Date(record.start_time).toLocaleTimeString(),
        suggestionDuration: suggestionText, // “建议时长”
        type: record.flag === "completed" ? "success" : "warning",
        status: record.flag === "completed" ? "已完成" : "中断",
        actualDuration: actualText, // “实际休息时间”
      };
    });
    getHealthData();
  } catch (error) {
    ElMessage.error("加载休息记录失败");
  }
};

// 模拟更新状态数据
const refreshStatus = () => {
  healthStatus.value = healthStatus.value.map((status) => {
    const newValue = Math.floor(Math.random() * 30) + 70;
    return {
      ...status,
      value: newValue,
      status:
        newValue >= 80 ? "success" : newValue >= 60 ? "warning" : "danger",
    };
  });

  environmentTips.value = environmentTips.value.map((tip) => {
    const randomChange = Math.random() * 10 - 5;
    let newValue;
    let newStatus = "success";

    switch (tip.id) {
      case 1: // 光线
        newValue = Math.floor(650 + randomChange * 50);
        newStatus =
          newValue > 1000 ? "danger" : newValue < 300 ? "warning" : "success";
        return { ...tip, value: `${newValue} lux`, status: newStatus };
      case 2: // 噪音
        newValue = Math.floor(35 + randomChange * 3);
        newStatus =
          newValue > 50 ? "danger" : newValue > 45 ? "warning" : "success";
        return { ...tip, value: `${newValue} dB`, status: newStatus };
      case 3: // 温度
        newValue = Math.floor(24 + randomChange);
        newStatus =
          newValue > 28 || newValue < 18
            ? "danger"
            : newValue > 26 || newValue < 20
            ? "warning"
            : "success";
        return { ...tip, value: `${newValue}℃`, status: newStatus };
      case 4: // 湿度
        newValue = Math.floor(45 + randomChange * 2);
        newStatus =
          newValue > 70 || newValue < 30
            ? "danger"
            : newValue > 60 || newValue < 40
            ? "warning"
            : "success";
        return { ...tip, value: `${newValue}%`, status: newStatus };
      default:
        return tip;
    }
  });
};

// 定时刷新状态
let statusTimer = null;

onMounted(() => {
  loadRestRecords();
});

onUnmounted(() => {
  if (statusTimer) {
    clearInterval(statusTimer);
  }
  if (timer) {
    clearInterval(timer);
  }
});

// 监听记录类型变化
watch(recordType, () => {
  loadRestRecords();
});

const fetchRestRecords = async () => {
  try {
    const response = await restApi.getRestRecords();
    if (Array.isArray(response)) {
      records.value = response.map((record) => ({
        ...record,
        start_time: new Date(record.start_time).toLocaleString(),
        duration: record.duration + "分钟",
      }));
      if (response.length === 0) {
        ElMessage.info("暂无休息记录");
      }
    } else {
      ElMessage.error("获取记录失败");
    }
  } catch (error) {
    console.error("获取记录失败:", error);
    ElMessage.error("获取记录失败");
  }
};
</script>

<style scoped>
.rest-area {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.timer-section {
  text-align: center;
  padding: 30px 0;
}

.timer-display {
  font-size: 64px;
  font-weight: bold;
  font-family: monospace;
  margin-bottom: 20px;
}

.timer-progress {
  width: 80%;
  margin: 0 auto 20px;
}

.timer-controls {
  margin-top: 20px;
}

.rest-suggestions {
  margin-top: 30px;
  border-top: 1px solid var(--el-border-color-lighter);
  padding-top: 20px;
}

.rest-suggestions h3 {
  margin-bottom: 20px;
  color: var(--el-text-color-primary);
}

.suggestion-card {
  cursor: pointer;
  transition: all 0.3s;
}

.suggestion-card.active {
  border-color: var(--el-color-primary);
  transform: translateY(-2px);
}

.suggestion-icon {
  font-size: 24px;
  color: var(--el-color-primary);
  margin-bottom: 10px;
}

.suggestion-content h4 {
  margin: 0 0 8px;
  color: var(--el-text-color-primary);
}

.suggestion-content p {
  color: var(--el-text-color-secondary);
  font-size: 12px;
  margin: 0;
}

.rest-records {
  margin-top: 20px;
}

.status-card {
  margin-bottom: 20px;
}

.status-items {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 15px;
}

.status-icon {
  font-size: 24px;
  color: var(--el-color-primary);
}

.status-info {
  flex: 1;
}

.status-label {
  margin-bottom: 8px;
  color: var(--el-text-color-regular);
}

.environment-card {
  margin-bottom: 20px;
}

.tip-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tip-content p {
  margin: 0;
  color: var(--el-text-color-regular);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .el-col {
    width: 100% !important;
  }

  .timer-display {
    font-size: 48px;
  }
}

/* 添加中断记录的样式 */
.interrupted-duration {
  color: #e6a23c;
  text-decoration: line-through;
  margin-right: 5px;
}

.actual-time {
  color: var(--el-text-color-secondary);
  font-size: 13px;
  margin: 5px 0;
}
</style>
